<template>
  <div class="personalCenter">
    <div class="personalCenterBg">
      <div class="personalCenterForm">
        <el-form
          ref="companyInfo_form"
          :model="itemEditData"
          label-width="120px"
          :rules="personalInfoRules"
        >
          <el-form-item label="用户头像">
            <el-upload
              class="avatar-uploader"
              :headers="{
                'x-auth-token': token,
              }"
              :action="uploadUrl"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleAvatarSuccess"
            >
              <img
                v-if="itemEditData.url && itemEditData.url !== ''"
                :src="imgBefore + itemEditData.url"
                class="avatarImg"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="登录账号">
            {{ itemEditData.username }}
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input
              v-model="itemEditData.nickname"
              placeholder="请输入用户昵称"
            ></el-input>
          </el-form-item>
          <el-form-item label="公司名称" prop="company">
            <el-input
              v-model="itemEditData.company"
              placeholder="请输入公司名称"
            ></el-input>
          </el-form-item>
          <div class="tips">提示：公司名称将在水质大屏显示，请正确填写</div>

          <el-form-item label="联系方式" prop="tel">
            <el-input v-model="itemEditData.tel" placeholder="请输入联系方式"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input
              v-model="itemEditData.email"
              placeholder="请输入电子邮箱"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div class="btnGroup">
        <el-button
          class="confirmBtn"
          type="primary"
          size="medium"
          icon="el-icon-edit"
          @click="editInformation('companyInfo_form')"
          >保 存</el-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import deepClone from "../utils/deepClone";
import MetaPageTable from "../components/MetaPageTable";
import { isWscnEmail, validateLetterNumberWord } from "../utils/validate";

export default {
  name: "personalCenter",
  components: {
    MetaPageTable,
  },
  data() {
    let checkName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("必填项不可为空"));
      } else {
        if (value.length > 50) {
          callback(new Error("内容录入过长"));
        } else if (!validateLetterNumberWord(value)) {
          callback(new Error("请准确输入名称"));
        } else {
          return callback();
        }
      }
    };
    let validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback();
      }
      if (!isWscnEmail(value)) {
        callback(new Error("请输入正确邮箱"));
      }
      callback();
    };
    let validatePhone = (rule, value, callback) => {
      if (value == "") {
        callback();
      }

      let phoneTest = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (!phoneTest.test(value)) {
        callback(new Error("请输入正确联系方式"));
      }
      callback();
    };
    return {
      token: localStorage.getItem("token"),
      uploadUrl: process.env.API_BASE_API + "admin/userCenter/img",
      imgBefore: process.env.PROGOO_FILE + "hyscanImg/file/",
      itemEditData: {
        id: "",
        username: "",
        nickname: "jd",
        url: "",
        company: "天津中科谱光",
        tel: "18188971930",
        email: "",
      },
      personalInfoRules: {
        nickname: [
          {
            required: true,
            validator: checkName,
            trigger: "blur",
          },
        ],
        company: [
          {
            required: true,
            validator: checkName,
            trigger: "blur",
          },
        ],
        tel: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { required: true, validator: validatePhone, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入电子邮箱", trigger: "blur" },
          { required: true, validator: validateEmail, trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.itemEditData.username = localStorage.getItem("username");
    this.getInformation();
  },
  methods: {
    getInformation() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/userCenter/search",
        method: "post",
        data: { username: this.itemEditData.username },
      }).then((res) => {
        if (res.data.code === 200) {
          this.itemEditData.id = res.data.result.id;
          this.itemEditData.email = res.data.result.email;
          this.itemEditData.nickname = res.data.result.nickname;
          this.itemEditData.tel = res.data.result.tel;
          this.itemEditData.company = res.data.result.company;
          this.itemEditData.url = res.data.result.url;
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    editInformation(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "admin/userCenter/edit",
            method: "post",
            data: this.itemEditData,
          }).then((res) => {
            if (res.data.code === 200) {
              this.$notify.success({
                title: "成功",
                message: "个人信息修改成功",
              });
              this.$router.go(0);
            } else {
              this.$notify.error({
                title: "错误",
                message: res.data.message,
              });
            }
          });
        } else {
        }
      });
    },

    handleAvatarSuccess(res) {
      this.itemEditData.url = res;
      this.$notify.success({
        title: "成功",
        message: "用户头像上传成功！",
      });
    },

    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ["jpg", "jpeg", "png"];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$notify.error({
          title: "错误",
          message: "只能上传jpg/png文件，且不超过5M",
        });
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$notify.error({
          title: "错误",
          message: "只能上传jpg/png文件，且不超过5M",
        });
        return false;
      }
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.personalCenter {
  width: 100%;
  height: 100%;
  box-sizing: border-box;

  padding: 15px;
  overflow-y: scroll;
  .personalCenterBg {
    height: 100%;
    display: flex;
    box-sizing: border-box;
    border: 1px solid #e4eaec;
    border-radius: 6px;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .personalCenterForm {
      margin: 50px;
      width: 60%;
      .avatarImg {
        width: 100px;
        height: 100px;
      }
      .tips {
        color: #fb9547;
        font-size: 13px;
        margin: 10px 0 10px 120px;
      }
    }
    .btnGroup {
      display: flex;
      flex-direction: row;
      margin-bottom: 50px;
      .confirmBtn {
        width: 120px;
        height: 40px;
        font-size: 16px;
      }
      .cancelBtn {
        width: 120px;
        height: 40px;
        font-size: 16px;
      }
    }
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
}
</style>
